package com.cgs.query.server.listener

import com.cgs.query.connection.ConnectionFactory
import com.cgs.query.event.QuerySourceEvent
import com.cgs.query.service.impl.jdbcEquals
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.ApplicationListener
import org.springframework.scheduling.annotation.Async

/**
 * 数据源监听：当数据源进行删除时,对ConnectionFactory进行相应的处理
 */
open class QuerySourceListener : ApplicationListener<QuerySourceEvent> {

    @Autowired
    private lateinit var connectionFactory: ConnectionFactory

    @Async
    override fun onApplicationEvent(event: QuerySourceEvent?) {
        when (event?.type) {
            QuerySourceEvent.Type.DELETE -> connectionFactory.removeConnectionBySourceId(event.sourceId)
            QuerySourceEvent.Type.UPDATE -> {
                //这里需要对比连接信息有没有改变
                if (event.originQuerySource?.jdbcEquals(event.newQuerySource) == false) {
                    connectionFactory.removeConnectionBySourceId(event.sourceId)
                }
            }
        }
    }
}